#Get objects
old_ws = ls()

#############
#Tables NVMS#
#############

useTable_nvms = mergedTable_nvms[!is.na(NVM_Violence_1_count) & (sample_ni_it)]

useTable_nvms[, NVM_Violence_1_count_ne := NVM_Violence_1_count - NVM_Violence_1_count_l3]
useTable_nvms[, NVM_Violence_1_binary_ne := NVM_Violence_1_count_ne > 0]
useTable_nvms[, NVM_Violence_1_deaths_ne := NVM_Violence_1_deaths - NVM_Violence_1_deaths_l3]
useTable_nvms[, NVM_Violence_1_deaths_binary_ne := NVM_Violence_1_deaths_ne > 0]

#################
#Events Analysis#
#################

#Model specifications
nb_specs = expand.grid(x = 'IT_win', y = c('NVM_Violence_1_count_ne', 'NVM_Violence_1_deaths_ne'), stringsAsFactors = F)
lm_specs = expand.grid(x = 'IT_win', y = c('NVM_Violence_1_binary_ne', 'NVM_Violence_1_deaths_binary_ne'), stringsAsFactors = F)

#Estimate models
nvms_nb_models = Map(function(y,x) glmnb_loop(y,x, useTable_nvms),
                     nb_specs$y, nb_specs$x)

nvms_lm_models = Map(function(y,x) lm_loop(y,x,  useTable_nvms),
                     lm_specs$y, lm_specs$x)

nvms_list = c(nvms_nb_models, nvms_lm_models)
nvms_se = lapply(nvms_list, function(x) cluster_errors(x, useTable_nvms[, cluster]) %>% diag %>% sqrt)


############
#Make Table#
############

table_list = c(nvms_list)
table_se = c(nvms_se)

#create table
n_clusters = useTable_nvms[, cluster] %>% unique %>% length

note_text = paste("Count models use negative binomial regression; binary outcomes use OLS. Standard errors are clustered by constituency-clusters. In the NVMS sample there are ", n_clusters, " clusters. Observations are constituencies in which the last seat was contested by Islamist and secular nationalist parties with a margin less than 1 percent.")

table = stargazer(table_list, se = table_se, type = 'latex', 
                  title = "Estimated Effects of Islamist Victory on Religious Violence (Excluding 3 months prior to elections)",
                  label = 'tab:main_violence_ni_it_nonelection',
                  model.names = F,
                  model.numbers = T,
                  column.separate = c(4),
                  column.labels = c('NVMS'),
                  multicolumn = T,
                  dep.var.labels = rep(c("Events","Deaths"), 2), 
                  add.lines = list(c('Count', rep(c('Y', 'Y', 'N', 'N'), 1)),
                                   c('Binary', rep(c('N', 'N', 'Y', 'Y'), 1))),
                  covariate.labels = c("Islamist Win"),
                  star.cutoffs = c(0.1, 0.05, 0.01),
                  #float.env = 'sidewaystable',
                  notes.align = 'l',
                  font.size = 'scriptsize',
                  keep.stat = 'n',
                  style = 'apsr')



write_latex(table[-10] %>% append(table[10], after = 10) %>% append("\\cmidrule(lr){2-5}", after = 10), note_text, './output/tables/table_e6.tex')


#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)
